package com.xq.controller;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.reflect.TypeToken;
import com.jfinal.log.Logger;
import com.xq.common.utils.XiaoQuUtils;
import com.xq.model.Topic;

public class TopicController extends BaseController
{

    private static Logger logger = Logger.getLogger(TopicController.class);

    public void send()
    {
        XQResponse response = null;
        String title = StringUtils.trim(getPara("title"));
        String content = StringUtils.trim(getPara("content"));
        String type = StringUtils.trim(getPara("type"));
        String userId = StringUtils.trim(getPara("userId"));
        String xiaoQuId = StringUtils.trim(getPara("xiaoQuId"));
        String parentId = StringUtils.trim(getPara("parentId"));
        // TODO:接收照片流
        // String photoFile = StringUtils.trim(getPara("photo"));
        Topic topic = new Topic();
        int status = 1;
        try
        {
            topic.set("title", title);
            topic.set("content", content);
            topic.set("type", type);
            topic.set("userId", userId);
            topic.set("xiaoQuId", xiaoQuId);
            topic.set("parentId", parentId);
            topic.set("sendTime", Calendar.getInstance().getTime());
            topic.save();
        } catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
            status = 500;
        }
        response = new XQResponse(status);
        renderJson(response);
    }

    public void query()
    {
        XQResponse response = new XQResponse(1);
        int start = getParaToInt("start");
        int limit = getParaToInt("limit");
        String xiaoQuId = getPara("xiaoQuId");
        String topicId = getPara("topicId");
        System.out.println("start: "+start +" limit: "+ limit+ " xiaoQuId: " +xiaoQuId + " topicId: "+topicId);
        try
        {
            List<Topic> topics = null;
            if (topicId != null)
            {
                topics = Topic.dao.findByTopicId(start, limit, Integer.parseInt(topicId));
            } else
            {
                topics = Topic.dao.findXiaoQuId(start, limit, Integer.parseInt(xiaoQuId));
            }
            String topicJson = XiaoQuUtils.GSON.toJson(topics,
                    new TypeToken<List<Topic>>()
                    {
                    }.getType());
            System.out.println(topicJson);
            response.setContent(topicJson);
        } catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
            response.setStatus(500);
        }

        renderJson(response);
    }

}
